package org.yuangu.privacyfinance.activities;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.privacy.accountmgr.R;

import org.yuangu.privacyfinance.activities.adapter.AbstractRecyclerViewHolder;
import org.yuangu.privacyfinance.activities.adapter.AccountWrapper;
import org.yuangu.privacyfinance.activities.adapter.EntityListAdapter;
import org.yuangu.privacyfinance.activities.adapter.OnItemClickListener;
import org.yuangu.privacyfinance.activities.dialog.AccountDialog;
import org.yuangu.privacyfinance.activities.helper.SwipeController;
import org.yuangu.privacyfinance.activities.viewmodel.AccountsViewModel;
import org.yuangu.privacyfinance.activities.viewmodel.BaseViewModel;
import org.yuangu.privacyfinance.domain.FinanceDatabase;
import org.yuangu.privacyfinance.domain.model.Account;
import org.yuangu.privacyfinance.helpers.CurrencyHelper;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

public class AccountsActivity extends BaseActivity implements OnItemClickListener<AccountWrapper> {
    private AccountsViewModel viewModel;
    private RecyclerView recyclerView;
    private AccountsAdapter accountsAdapter;

    @Override
    protected Class<? extends BaseViewModel> getViewModelClass() {
        return AccountsViewModel.class;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        viewModel = (AccountsViewModel) super.viewModel;

        accountsAdapter = new AccountsAdapter(this, viewModel.getAccounts());

        accountsAdapter.onItemClick(this);

        setContent(R.layout.content_recycler);
        addFab(R.layout.fab_add, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openAccountDialog(null);
            }
        });

        recyclerView = findViewById(R.id.recycler_view);
        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 1);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(accountsAdapter);

        SwipeController.SwipeControllerAction deleteAction = new SwipeController.SwipeControllerAction() {
            @Override
            public void onClick(int position) {
                deleteAccount(viewModel.getAccounts().getValue().get(position).getAccount());
            }

            @Override
            public Drawable getIcon() {
                return ContextCompat.getDrawable(AccountsActivity.this, R.drawable.ic_delete_red_24dp);
            }
        };

        final SwipeController swipeController = new SwipeController(this, deleteAction, deleteAction);

        ItemTouchHelper itemTouchhelper = new ItemTouchHelper(swipeController);
        itemTouchhelper.attachToRecyclerView(recyclerView);

        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                swipeController.onDraw(c);
            }
        });
    }

    private void deleteAccount(final Account account) {
        if (viewModel.getAccounts().getValue().size() > 1) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.account_delete_action);
            builder.setMessage(Html.fromHtml(getResources().getString(R.string.account_delete_question, account.getName())));
            builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    FinanceDatabase.getInstance().accountDao().deleteAsync(account);
                    Toast.makeText(getBaseContext(), R.string.account_deleted_msg, Toast.LENGTH_SHORT).show();
                }
            });
            builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                }
            });
            builder.create().show();
        } else {
            Toast.makeText(getBaseContext(), R.string.account_last_not_deleteable, Toast.LENGTH_LONG).show();
        }
    }

    public static final String EXTRA_CATEGORY_ID = "org.secuso.privacyfriendlyfinance.EXTRA_CATEGORY_ID";

    private void openAccountDialog(Account account) {
        Bundle args = new Bundle();
        if (account == null) {
        } else {
            args.putLong(EXTRA_CATEGORY_ID, account.getId());
        }

        AccountDialog accountDialog = new AccountDialog();
        accountDialog.setArguments(args);

        accountDialog.show(getSupportFragmentManager(), "CategoryDialog");
    }

    @Override
    public void onItemClick(AccountWrapper item) {
        Intent intent = new Intent(this, AccountActivity.class);
        intent.putExtra(AccountActivity.EXTRA_ACCOUNT_ID, item.getId());
        startActivity(intent);
    }


    public class AccountViewHolder extends AbstractRecyclerViewHolder {
        private TextView tvAccountName;
        private TextView tvAccountBalance;
        private TextView tvAccountBalanceMonth;

        public AccountViewHolder(@NonNull View itemView, Context context) {
            super(itemView, context);
            tvAccountName = itemView.findViewById(R.id.textView_account_name);
            tvAccountBalance = itemView.findViewById(R.id.textView_balance);
            tvAccountBalanceMonth = itemView.findViewById(R.id.textView_balance_month_start);
        }

        public void setAccountName(String name) {
            tvAccountName.setText(name);
        }

        public void setBalance(Long balance) {
            CurrencyHelper.setBalance(balance, tvAccountBalance);
        }

        public void setBalanceMonthStart(Long balance) {
            CurrencyHelper.setBalance(balance, tvAccountBalanceMonth);
        }
    }

    public class AccountsAdapter extends EntityListAdapter<AccountWrapper, AccountViewHolder> {
        public AccountsAdapter(BaseActivity context, LiveData<List<AccountWrapper>> data) {
            super(context, data);
        }

        @NonNull
        @Override
        public AccountViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
            View viewItem = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.card_account, parent, false);
            return new AccountViewHolder(viewItem, context);
        }

        @Override
        public void onBindViewHolder(@NonNull final AccountViewHolder holder, int index) {
            super.onBindViewHolder(holder, index);
            AccountWrapper wrapper = getItem(index);
            holder.setAccountName(wrapper.getAccount().getName());

            wrapper.getCurrentBalance().observe(context, new Observer<Long>() {
                @Override
                public void onChanged(@Nullable Long balance) {
                    holder.setBalance(balance);
                }
            });

            wrapper.getStartOfMonthBalance().observe(context, new Observer<Long>() {
                @Override
                public void onChanged(@Nullable Long balance) {
                    holder.setBalanceMonthStart(balance);
                }
            });
        }
    }
}
